from flask import Flask, render_template, request, jsonify, send_file, session, redirect, url_for
import os
import json
import time
import threading
from datetime import datetime
import pandas as pd
from spider.anjuke_spider import EnhancedAnjukeRentSpider
from spider.database import DatabaseManager
import config

app = Flask(__name__)
app.config.from_object(config)
app.secret_key = 'your-secret-key-here'  # 请在生产环境中更改

# 存储任务状态和结果
tasks = {}
TASKS_FILE = 'tasks_status.json'


def save_tasks_to_file():
    """将任务状态保存到文件"""
    tasks_data = {}
    for task_id, task in tasks.items():
        tasks_data[task_id] = {
            'task_id': task.task_id,
            'status': task.status,
            'progress': task.progress,
            'message': task.message,
            'results_count': len(task.results),
            'start_time': task.start_time.isoformat() if task.start_time else None,
            'end_time': task.end_time.isoformat() if task.end_time else None,
            'config': task.config,
            'result_file': getattr(task, 'result_file', None)
        }

    with open(TASKS_FILE, 'w', encoding='utf-8') as f:
        json.dump(tasks_data, f, ensure_ascii=False, indent=2)


def load_tasks_from_file():
    """从文件加载任务状态"""
    global tasks
    if os.path.exists(TASKS_FILE):
        try:
            with open(TASKS_FILE, 'r', encoding='utf-8') as f:
                tasks_data = json.load(f)

            for task_id, task_data in tasks_data.items():
                task = SpiderTask(task_id, task_data['config'])
                task.status = task_data['status']
                task.progress = task_data['progress']
                task.message = task_data['message']
                task.results = []  # 不保存结果数据，太大了
                task.start_time = datetime.fromisoformat(task_data['start_time']) if task_data['start_time'] else None
                task.end_time = datetime.fromisoformat(task_data['end_time']) if task_data['end_time'] else None
                if task_data.get('result_file'):
                    task.result_file = task_data['result_file']

                tasks[task_id] = task
        except Exception as e:
            print(f"加载任务状态失败: {e}")


# 在应用启动时加载任务状态
load_tasks_from_file()

class SpiderTask:
    def __init__(self, task_id, config):
        self.task_id = task_id
        self.config = config
        self.status = 'pending'  # pending, running, completed, error
        self.progress = 0
        self.message = ''
        self.results = []
        self.start_time = None
        self.end_time = None
        self.spider = None
        self.result_file = None

    def update_status(self, status, progress=None, message=None):
        """更新任务状态并自动保存"""
        self.status = status
        if progress is not None:
            self.progress = progress
        if message is not None:
            self.message = message

        # 自动保存到文件
        save_tasks_to_file()


    def run(self):
        try:
            self.status = 'running'
            self.start_time = datetime.now()
            self.message = '开始爬取任务...'

            # 初始化爬虫
            self.spider = EnhancedAnjukeRentSpider(config=self.config)

            # 执行爬取
            houses = self.spider.crawl(
                city=self.config.get('city'),
                district=self.config.get('district'),
                min_price=self.config.get('min_price'),
                max_price=self.config.get('max_price'),
                room_type=self.config.get('room_type'),
                source_type=self.config.get('source_type'),
                max_pages=self.config.get('max_pages', 5),
                get_details=self.config.get('get_details', False)
            )

            self.progress = 100
            self.results = houses
            self.status = 'completed'
            self.message = f'爬取完成！共获取 {len(houses)} 条房源信息'
            self.end_time = datetime.now()

            # 保存结果到文件
            if houses:
                timestamp = int(time.time())
                filename = f"results_{self.task_id}_{timestamp}.xlsx"
                filepath = os.path.join('uploads', filename)
                self.spider.save_to_excel(houses, filepath)
                self.result_file = filepath

            # 关闭爬虫资源
            if self.spider:
                self.spider.close()

        except Exception as e:
            self.status = 'error'
            self.message = f'爬取过程中出错: {str(e)}'
            self.end_time = datetime.now()

            if self.spider:
                self.spider.close()


def run_spider_task(task):
    """在后台线程中运行爬虫任务"""
    thread = threading.Thread(target=task.run)
    thread.daemon = True
    thread.start()


@app.route('/')
def index():
    """首页"""
    return render_template('index.html')


@app.route('/start_task', methods=['POST'])
def start_task():
    """开始新的爬虫任务"""
    try:
        data = request.get_json()

        # 生成任务ID
        task_id = f"task_{int(time.time())}_{len(tasks)}"

        # 创建任务配置
        task_config = {
            'city': data.get('city'),
            'district': data.get('district'),
            'min_price': data.get('min_price'),
            'max_price': data.get('max_price'),
            'room_type': data.get('room_type'),
            'source_type': data.get('source_type'),
            'max_pages': int(data.get('max_pages', 5)),
            'get_details': data.get('get_details', False),
            'database': config.DATABASE_CONFIG
        }

        # 创建任务
        task = SpiderTask(task_id, task_config)
        tasks[task_id] = task

        # 在后台运行任务
        run_spider_task(task)

        return jsonify({
            'success': True,
            'task_id': task_id,
            'message': '任务已开始执行'
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'启动任务失败: {str(e)}'
        })


@app.route('/task_status/<task_id>')
def task_status(task_id):
    """获取任务状态"""
    task = tasks.get(task_id)
    if not task:
        return jsonify({'error': '任务不存在'})

    return jsonify({
        'task_id': task.task_id,
        'status': task.status,
        'progress': task.progress,
        'message': task.message,
        'results_count': len(task.results),
        'start_time': task.start_time.isoformat() if task.start_time else None,
        'end_time': task.end_time.isoformat() if task.end_time else None
    })


@app.route('/task_results/<task_id>')
def task_results(task_id):
    """获取任务结果"""
    task = tasks.get(task_id)
    if not task:
        return jsonify({'error': '任务不存在'})

    if task.status != 'completed':
        return jsonify({'error': '任务尚未完成'})

    # 只返回前100条结果用于预览
    preview_results = task.results[:100]

    return jsonify({
        'total_count': len(task.results),
        'preview_results': preview_results,
        'result_file': task.result_file if hasattr(task, 'result_file') else None
    })


@app.route('/download/<task_id>')
def download_results(task_id):
    """下载结果文件"""
    task = tasks.get(task_id)
    if not task or not hasattr(task, 'result_file') or not task.result_file:
        return "文件不存在", 404

    if os.path.exists(task.result_file):
        filename = f"安居客租房数据_{task_id}.xlsx"
        return send_file(task.result_file, as_attachment=True, download_name=filename)
    else:
        return "文件不存在", 404


@app.route('/get_city_districts/<city>')
def get_city_districts(city):
    """获取城市区域列表"""
    spider = EnhancedAnjukeRentSpider()
    city_info = spider.get_city_info(city)
    spider.close()

    if city_info and 'districts' in city_info:
        districts = list(city_info['districts'].keys())
        return jsonify({'districts': districts})
    else:
        return jsonify({'districts': []})


@app.route('/batch_tasks')
def batch_tasks():
    """批量任务管理页面"""
    return render_template('batch_tasks.html')


@app.route('/upload_batch_config', methods=['POST'])
def upload_batch_config():
    """上传批量任务配置文件"""
    if 'file' not in request.files:
        return jsonify({'success': False, 'message': '没有选择文件'})

    file = request.files['file']
    if file.filename == '':
        return jsonify({'success': False, 'message': '没有选择文件'})

    if file and file.filename.endswith('.json'):
        try:
            content = file.read().decode('utf-8')
            config_data = json.loads(content)

            # 验证配置格式
            if not isinstance(config_data, list):
                return jsonify({'success': False, 'message': '配置文件格式错误，应该是任务列表'})

            # 启动批量任务
            batch_tasks = []
            for task_config in config_data:
                task_id = f"batch_{int(time.time())}_{len(batch_tasks)}"

                full_config = {
                    'city': task_config.get('city'),
                    'district': task_config.get('district'),
                    'min_price': task_config.get('min_price'),
                    'max_price': task_config.get('max_price'),
                    'room_type': task_config.get('room_type'),
                    'source_type': task_config.get('source_type'),
                    'max_pages': task_config.get('max_pages', 3),
                    'get_details': task_config.get('get_details', False),
                    'database': config.DATABASE_CONFIG
                }

                task = SpiderTask(task_id, full_config)
                tasks[task_id] = task
                batch_tasks.append(task_id)

                # 添加延迟后启动
                time.sleep(2)
                run_spider_task(task)

            return jsonify({
                'success': True,
                'message': f'已启动 {len(batch_tasks)} 个批量任务',
                'task_ids': batch_tasks
            })

        except Exception as e:
            return jsonify({'success': False, 'message': f'配置文件解析失败: {str(e)}'})

    return jsonify({'success': False, 'message': '只支持JSON格式文件'})


@app.route('/get_all_tasks')
def get_all_tasks():
    """获取所有任务状态"""
    task_list = []
    for task_id, task in tasks.items():
        task_list.append({
            'task_id': task_id,
            'status': task.status,
            'progress': task.progress,
            'message': task.message,
            'results_count': len(task.results),
            'start_time': task.start_time.isoformat() if task.start_time else None,
            'config': {
                'city': task.config.get('city'),
                'district': task.config.get('district')
            }
        })

    # 按开始时间倒序排列
    task_list.sort(key=lambda x: x['start_time'] or '', reverse=True)

    return jsonify({'tasks': task_list})


# 在 app.py 中添加以下路由

@app.route('/data_management')
def data_management():
    """数据管理页面"""
    return render_template('data_management.html')


@app.route('/api/houses')
def get_houses():
    """获取房源数据API"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        city = request.args.get('city', '')
        district = request.args.get('district', '')
        min_price = request.args.get('min_price', 0, type=float)
        max_price = request.args.get('max_price', 0, type=float)
        room_type = request.args.get('room_type', '')
        source_type = request.args.get('source_type', '')
        search = request.args.get('search', '')
        is_favorite = request.args.get('is_favorite', '')  # 添加收藏状态筛选

        # 计算分页
        offset = (page - 1) * per_page

        # 构建查询条件
        db_manager = DatabaseManager(config.DATABASE_CONFIG)
        where_conditions = []
        params = []

        if city:
            where_conditions.append("city = %s")
            params.append(city)
        if district:
            where_conditions.append("district = %s")
            params.append(district)
        if min_price > 0:
            where_conditions.append("price >= %s")
            params.append(min_price)
        if max_price > 0:
            where_conditions.append("price <= %s")
            params.append(max_price)
        if room_type:
            where_conditions.append("room_type LIKE %s")
            params.append(f'%{room_type}%')
        if source_type:
            where_conditions.append("source_type = %s")
            params.append(source_type)
        if search:
            where_conditions.append("(title LIKE %s OR address LIKE %s OR agent LIKE %s OR house_code LIKE %s)")
            params.extend([f'%{search}%', f'%{search}%', f'%{search}%',f'%{search}%'])

            # 添加收藏状态筛选
        if is_favorite == '1':
            where_conditions.append("f.house_id IS NOT NULL")
        elif is_favorite == '0':
            where_conditions.append("f.house_id IS NULL")

        # 构建WHERE子句
        where_clause = ""
        if where_conditions:
            where_clause = "WHERE " + " AND ".join(where_conditions)

        # 查询数据总数
        count_query = f"SELECT COUNT(*) as total FROM house_info {where_clause}"
        count_result = db_manager.execute_query(count_query, tuple(params), fetch=True)
        total_count = count_result[0]['total'] if count_result else 0

        # 查询数据（包含收藏状态）
        query = f"""
                   SELECT h.*, 
                          CASE WHEN f.house_id IS NOT NULL THEN 1 ELSE 0 END as is_favorite
                   FROM house_info h
                   LEFT JOIN favorites f ON h.id = f.house_id
                   {where_clause}
                   ORDER BY h.crawl_time DESC 
                   LIMIT %s OFFSET %s
               """
        params.extend([per_page, offset])

        houses = db_manager.execute_query(query, tuple(params), fetch=True)
        db_manager.close()

        # 处理可能的空结果
        if houses is None:
            houses = []  # 确保 houses 是一个可迭代对象

        # 格式化数据
        formatted_houses = []
        for house in houses:
            formatted_house = dict(house)
            # 格式化时间
            if formatted_house.get('crawl_time'):
                formatted_house['crawl_time'] = formatted_house['crawl_time'].strftime('%Y-%m-%d %H:%M:%S')
            if formatted_house.get('created_at'):
                formatted_house['created_at'] = formatted_house['created_at'].strftime('%Y-%m-%d %H:%M:%S')
            if formatted_house.get('updated_at'):
                formatted_house['updated_at'] = formatted_house['updated_at'].strftime('%Y-%m-%d %H:%M:%S')
            formatted_houses.append(formatted_house)

        return jsonify({
            'success': True,
            'data': formatted_houses,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': total_count,
                'pages': (total_count + per_page - 1) // per_page
            }
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取数据失败: {str(e)}'
        })


@app.route('/api/houses/<int:house_id>', methods=['GET'])
def get_house_detail(house_id):
    """获取单个房源详情"""
    try:
        db_manager = DatabaseManager(config.DATABASE_CONFIG)
        query = "SELECT * FROM house_info WHERE id = %s"
        result = db_manager.execute_query(query, (house_id,), fetch=True)
        db_manager.close()

        if result:
            house = dict(result[0])
            # 格式化时间
            if house.get('crawl_time'):
                house['crawl_time'] = house['crawl_time'].strftime('%Y-%m-%d %H:%M:%S')
            if house.get('created_at'):
                house['created_at'] = house['created_at'].strftime('%Y-%m-%d %H:%M:%S')
            if house.get('updated_at'):
                house['updated_at'] = house['updated_at'].strftime('%Y-%m-%d %H:%M:%S')

            return jsonify({
                'success': True,
                'data': house
            })
        else:
            return jsonify({
                'success': False,
                'message': '房源不存在'
            })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取房源详情失败: {str(e)}'
        })


@app.route('/api/houses/<int:house_id>/favorite', methods=['POST'])
def toggle_favorite(house_id):
    """切换房源收藏状态（无需用户系统，基于房源ID直接操作）"""
    try:
        db_manager = DatabaseManager(config.DATABASE_CONFIG)

        # 1. 检查房源是否存在
        house_query = "SELECT id FROM house_info WHERE id = %s"
        house_exists = db_manager.execute_query(house_query, (house_id,), fetch=True)
        if not house_exists:
            db_manager.close()
            return jsonify({
                'success': False,
                'message': '房源不存在'
            })

        # 2. 检查房源是否已收藏（根据house_id查询favorites表）
        favorite_query = "SELECT id FROM favorites WHERE house_id = %s"
        is_favorite = db_manager.execute_query(favorite_query, (house_id,), fetch=True)

        if is_favorite:
            # 3. 已收藏：取消收藏（删除收藏记录）
            delete_query = "DELETE FROM favorites WHERE house_id = %s"
            db_manager.execute_query(delete_query, (house_id,))
            db_manager.commit()
            db_manager.close()
            return jsonify({
                'success': True,
                'data': {'is_favorite': False},
                'message': '取消收藏成功'
            })
        else:
            # 4. 未收藏：添加收藏（插入收藏记录）
            insert_query = "INSERT INTO favorites (house_id, created_at) VALUES (%s, NOW())"
            db_manager.execute_query(insert_query, (house_id,))
            db_manager.commit()
            db_manager.close()
            return jsonify({
                'success': True,
                'data': {'is_favorite': True},
                'message': '收藏成功'
            })

    except Exception as e:
        db_manager.rollback()
        db_manager.close()
        return jsonify({
            'success': False,
            'message': f'操作失败: {str(e)}'
        })

@app.route('/api/houses/stats')
def get_houses_stats():
    """获取数据统计信息"""
    try:
        db_manager = DatabaseManager(config.DATABASE_CONFIG)

        # 总数据量
        total_query = "SELECT COUNT(*) as total FROM house_info"
        total_result = db_manager.execute_query(total_query, fetch=True)
        total_count = total_result[0]['total'] if total_result else 0

        # 城市分布
        city_query = """
            SELECT city, COUNT(*) as count 
            FROM house_info 
            GROUP BY city 
            ORDER BY count DESC
        """
        city_stats = db_manager.execute_query(city_query, fetch=True)

        # 价格统计
        price_query = """
            SELECT 
                MIN(price) as min_price,
                MAX(price) as max_price,
                AVG(price) as avg_price,
                COUNT(*) as total
            FROM house_info 
            WHERE price > 0
        """
        price_stats = db_manager.execute_query(price_query, fetch=True)

        db_manager.close()

        stats = {
            'total_count': total_count,
            'city_distribution': city_stats or [],
            'price_stats': price_stats[0] if price_stats else {}
        }

        return jsonify({
            'success': True,
            'data': stats
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取统计信息失败: {str(e)}'
        })


# -------------------------------------

# 在 app.py 中添加以下路由

@app.route('/api/houses/<int:house_id>', methods=['PUT'])
def update_house(house_id):
    """更新房源信息"""
    try:
        data = request.get_json()

        if not data:
            return jsonify({
                'success': False,
                'message': '请求数据不能为空'
            })

        # 验证必要字段
        if not data.get('title'):
            return jsonify({
                'success': False,
                'message': '房源标题不能为空'
            })

        # 构建更新字段和参数
        update_fields = []
        params = []

        # 可更新的字段列表
        updatable_fields = [
            'title', 'price', 'room_type', 'area', 'floor_info', 'total_floors',
            'address', 'tags', 'agent', 'features', 'house_code', 'payment_method',
            'detailed_layout', 'orientation', 'decoration', 'facilities',
            'description', 'rental_requirements', 'city', 'district', 'source_type'
        ]

        for field in updatable_fields:
            if field in data:
                update_fields.append(f"{field} = %s")
                params.append(data[field])

        if not update_fields:
            return jsonify({
                'success': False,
                'message': '没有可更新的字段'
            })

        # 添加更新时间
        update_fields.append("updated_at = CURRENT_TIMESTAMP")

        # 添加WHERE条件
        params.append(house_id)

        # 执行更新
        db_manager = DatabaseManager(config.DATABASE_CONFIG)
        query = f"UPDATE house_info SET {', '.join(update_fields)} WHERE id = %s"

        result = db_manager.execute_query(query, tuple(params))
        db_manager.close()

        if result:
            return jsonify({
                'success': True,
                'message': '房源信息更新成功'
            })
        else:
            return jsonify({
                'success': False,
                'message': '更新房源信息失败'
            })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'更新房源信息失败: {str(e)}'
        })


@app.route('/api/houses/<int:house_id>', methods=['DELETE'])
def delete_house(house_id):
    """删除房源信息"""
    try:
        # 先检查房源是否存在
        db_manager = DatabaseManager(config.DATABASE_CONFIG)
        check_query = "SELECT id FROM house_info WHERE id = %s"
        check_result = db_manager.execute_query(check_query, (house_id,), fetch=True)

        if not check_result:
            db_manager.close()
            return jsonify({
                'success': False,
                'message': '房源不存在'
            })

        # 执行删除
        delete_query = "DELETE FROM house_info WHERE id = %s"
        result = db_manager.execute_query(delete_query, (house_id,))
        db_manager.close()

        if result:
            return jsonify({
                'success': True,
                'message': '房源删除成功'
            })
        else:
            return jsonify({
                'success': False,
                'message': '删除房源失败'
            })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'删除房源失败: {str(e)}'
        })


@app.route('/api/houses/batch_delete', methods=['POST'])
def batch_delete_houses():
    """批量删除房源信息"""
    try:
        data = request.get_json()

        if not data or 'ids' not in data or not data['ids']:
            return jsonify({
                'success': False,
                'message': '请选择要删除的房源'
            })

        house_ids = data['ids']

        # 验证ID列表
        if not all(isinstance(id, int) for id in house_ids):
            return jsonify({
                'success': False,
                'message': '无效的房源ID'
            })

        # 构建IN查询参数
        placeholders = ','.join(['%s'] * len(house_ids))

        db_manager = DatabaseManager(config.DATABASE_CONFIG)
        delete_query = f"DELETE FROM house_info WHERE id IN ({placeholders})"

        result = db_manager.execute_query(delete_query, tuple(house_ids))
        db_manager.close()

        if result:
            return jsonify({
                'success': True,
                'message': f'成功删除 {len(house_ids)} 条房源记录'
            })
        else:
            return jsonify({
                'success': False,
                'message': '批量删除失败'
            })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'批量删除失败: {str(e)}'
        })


@app.route('/api/houses/export', methods=['POST'])
def export_houses():
    """导出房源数据"""
    try:
        data = request.get_json() or {}

        # 获取导出参数
        export_format = data.get('format', 'excel')
        filters = data.get('filters', {})
        columns = data.get('columns', [])

        # 验证导出格式
        if export_format not in ['excel', 'csv']:
            return jsonify({
                'success': False,
                'message': '不支持的导出格式'
            })

        # 构建查询条件
        db_manager = DatabaseManager(config.DATABASE_CONFIG)
        where_conditions = []
        params = []

        # 处理筛选条件
        if filters.get('city'):
            where_conditions.append("city = %s")
            params.append(filters['city'])
        if filters.get('district'):
            where_conditions.append("district = %s")
            params.append(filters['district'])
        if filters.get('min_price'):
            where_conditions.append("price >= %s")
            params.append(float(filters['min_price']))
        if filters.get('max_price'):
            where_conditions.append("price <= %s")
            params.append(float(filters['max_price']))
        if filters.get('room_type'):
            where_conditions.append("room_type LIKE %s")
            params.append(f'%{filters["room_type"]}%')
        if filters.get('source_type'):
            where_conditions.append("source_type = %s")
            params.append(filters['source_type'])
        if filters.get('search'):
            where_conditions.append("(title LIKE %s OR address LIKE %s OR agent LIKE %s)")
            params.extend([f'%{filters["search"]}%', f'%{filters["search"]}%', f'%{filters["search"]}%'])

        # 构建WHERE子句
        where_clause = ""
        if where_conditions:
            where_clause = "WHERE " + " AND ".join(where_conditions)

        # 查询数据
        query = f"SELECT * FROM house_info {where_clause} ORDER BY crawl_time DESC"
        houses = db_manager.execute_query(query, tuple(params), fetch=True)
        db_manager.close()

        if not houses:
            return jsonify({
                'success': False,
                'message': '没有数据可导出'
            })

        # 转换为DataFrame
        df = pd.DataFrame(houses)

        # 选择要导出的列
        if columns:
            # 确保包含必要的列
            essential_columns = ['id', 'title', 'price', 'room_type', 'area', 'city', 'district']
            export_columns = list(set(columns + essential_columns))
            df = df[export_columns]

        # 重命名列名为中文
        column_mapping = {
            'id': 'ID',
            'title': '标题',
            'price': '价格(元/月)',
            'room_type': '户型',
            'area': '面积(㎡)',
            'floor_info': '楼层信息',
            'total_floors': '总楼层',
            'address': '地址',
            'tags': '标签',
            'agent': '经纪人',
            'features': '特色',
            'link': '链接',
            'crawl_time': '爬取时间',
            'house_code': '房屋编码',
            'payment_method': '付款方式',
            'detailed_layout': '详细户型',
            'orientation': '朝向',
            'decoration': '装修',
            'facilities': '配套设施',
            'description': '房源描述',
            'rental_requirements': '出租要求',
            'city': '城市',
            'district': '区域',
            'source_type': '来源类型',
            'created_at': '创建时间',
            'updated_at': '更新时间'
        }

        df.rename(columns=column_mapping, inplace=True)

        # 生成文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"房源数据导出_{timestamp}"

        if export_format == 'excel':
            filename += '.xlsx'
            filepath = os.path.join('uploads', filename)

            # 保存为Excel
            df.to_excel(filepath, index=False, engine='openpyxl')

            # 返回下载链接
            return jsonify({
                'success': True,
                'message': f'成功导出 {len(houses)} 条数据',
                'download_url': f'/download_export/{filename}'
            })

        else:  # csv
            filename += '.csv'
            filepath = os.path.join('uploads', filename)

            # 保存为CSV
            df.to_csv(filepath, index=False, encoding='utf-8-sig')

            # 返回下载链接
            return jsonify({
                'success': True,
                'message': f'成功导出 {len(houses)} 条数据',
                'download_url': f'/download_export/{filename}'
            })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'导出数据失败: {str(e)}'
        })


@app.route('/download_export/<filename>')
def download_export(filename):
    """下载导出文件"""
    try:
        filepath = os.path.join('uploads', filename)

        if os.path.exists(filepath):
            return send_file(filepath, as_attachment=True, download_name=filename)
        else:
            return "文件不存在", 404

    except Exception as e:
        return f"下载文件失败: {str(e)}", 500


@app.route('/api/houses/columns')
def get_available_columns():
    """获取可用的数据列"""
    columns = [
        {'key': 'id', 'name': 'ID', 'description': '唯一标识'},
        {'key': 'title', 'name': '标题', 'description': '房源标题'},
        {'key': 'price', 'name': '价格', 'description': '月租金(元)'},
        {'key': 'room_type', 'name': '户型', 'description': '房间类型'},
        {'key': 'area', 'name': '面积', 'description': '房屋面积(㎡)'},
        {'key': 'floor_info', 'name': '楼层信息', 'description': '所在楼层'},
        {'key': 'total_floors', 'name': '总楼层', 'description': '建筑总楼层'},
        {'key': 'address', 'name': '地址', 'description': '详细地址'},
        {'key': 'tags', 'name': '标签', 'description': '房源标签'},
        {'key': 'agent', 'name': '经纪人', 'description': '经纪人信息'},
        {'key': 'features', 'name': '特色', 'description': '房源特色'},
        {'key': 'link', 'name': '链接', 'description': '原始页面链接'},
        {'key': 'crawl_time', 'name': '爬取时间', 'description': '数据爬取时间'},
        {'key': 'house_code', 'name': '房屋编码', 'description': '房屋唯一编码'},
        {'key': 'payment_method', 'name': '付款方式', 'description': '租金支付方式'},
        {'key': 'detailed_layout', 'name': '详细户型', 'description': '详细户型信息'},
        {'key': 'orientation', 'name': '朝向', 'description': '房屋朝向'},
        {'key': 'decoration', 'name': '装修', 'description': '装修情况'},
        {'key': 'facilities', 'name': '配套设施', 'description': '家居设施'},
        {'key': 'description', 'name': '房源描述', 'description': '房源详细描述'},
        {'key': 'rental_requirements', 'name': '出租要求', 'description': '出租条件要求'},
        {'key': 'city', 'name': '城市', 'description': '所在城市'},
        {'key': 'district', 'name': '区域', 'description': '所在区域'},
        {'key': 'source_type', 'name': '来源类型', 'description': '房源来源'},
        {'key': 'created_at', 'name': '创建时间', 'description': '数据创建时间'},
        {'key': 'updated_at', 'name': '更新时间', 'description': '最后更新时间'}
    ]

    return jsonify({
        'success': True,
        'data': columns
    })

@app.route('/test_database')
def test_database():
    """测试数据库连接"""
    try:
        db_manager = DatabaseManager(config.DATABASE_CONFIG)
        if db_manager.connection:
            result = db_manager.execute_query("SELECT COUNT(*) as count FROM house_info", fetch=True)
            count = result[0][0] if result else 0
            db_manager.close()
            return jsonify({
                'success': True,
                'message': f'数据库连接成功，当前共有 {count} 条房源记录'
            })
        else:
            return jsonify({'success': False, 'message': '数据库连接失败'})
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库连接异常: {str(e)}'})


if __name__ == '__main__':
    # 确保上传目录存在
    os.makedirs('uploads', exist_ok=True)
    os.makedirs('static', exist_ok=True)
    os.makedirs('templates', exist_ok=True)

    app.run(debug=True, host='0.0.0.0', port=5000,use_reloader=False)